import React from 'react'
import PropTypes from 'prop-types'
import Component, { mapStateToProps, mapDispatchToProps } from '@components/Component'
import { connect } from 'react-redux'
import { Radio, Table, message, Button, Space, Modal, Form, Select, InputNumber } from 'antd'
import { ExclamationCircleOutlined } from '@ant-design/icons'
import style from './CaseDocument.module.less'
import moment from 'moment'
import Text from '@components/Text'
const { Item } = Form
const { Option } = Select
const { confirm } = Modal
const columns = function () {
  const list = [
    {
      title: '文件名称',
      dataIndex: 'title',
      key: 'title'
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type'
    },
    {
      title: '文书流水号',
      dataIndex: 'serialno_desc',
      key: 'serialno_desc'
    },
    {
      title: '发送对象',
      dataIndex: 'receiver',
      key: 'receiver'
    },
    {
      title: '发文日期',
      dataIndex: 'creater_datetime',
      key: 'creater_datetime',
      render (v) {
        if (v) {
          return moment(v * 1000).format('YYYY-MM-DD')
        }
        return ''
      }
    },
    {
      title: '份数',
      dataIndex: 'num',
      key: 'num'
    },
    {
      title: '经办人',
      dataIndex: 'creator',
      key: 'creator'
    },
    {
      title: '操作',
      dataIndex: 'editable',
      key: 'editable',
      width: 200,
      render: (v, l) => {
        const u = this.props.userInfo
        const isCreator = l.creatorid === u.id
        return (
          <Space>
            <a onClick={() => this.$readerPdf(l.title, l.id, this.props.caseDetail.id)}>查看</a>
            {l.serialno && isCreator ? <a onClick={() => this.showModifyNum(l)}>修改流水号</a> : null}
            {isCreator ? <a onClick={() => this.delConfirm(l)}>作废</a> : null}
          </Space>
        )
      }
    }
  ]
  return list
}

class CaseDocument extends Component {
  state = {
    type: '',
    loading: false,
    list: [],
    visible: false,
    numVisible: false,
    templateList: [],
    fileTypes: [], // 文书类型
    modifyDoc: {} // 被修改的文书对象
  }

  formRef = React.createRef()
  numFormRef = React.createRef()

  changeStatus (v) {
    this.setState({
      type: v.target.value
    })
  }

  // 获取文书列表
  getList () {
    this.setState({ loading: true })
    this.$get(`/api/vendor/case/file/${this.props.caseDetail.id}`, {
      page_size: 10000
    })
      .then(res => {
        this.setState({ loading: false })
        if (res.status === 1) {
          this.setState({
            list: res.data.list
          })
        } else {
          message.warning(res.message)
        }
      }).catch(res => this.setState({ loading: false }))
  }

  // 获取文书模板列表
  getTemplateList () {
    const hide = message.loading('获取模板中', 120)
    this.$get('/api/xapc/file_template', {
      page_size: 10000
    })
      .then(res => {
        hide()
        if (res.status === 1) {
          this.setState({
            templateList: res.data.list.filter(li => li.user_define === 2)
          })
        } else {
          message.warning(res.message)
        }
      })
      .catch(() => hide())
  }

  // 根据模板code生成文书
  createDocumentByTemplate (d) {
    const hide = message.loading('文书生成中', 120)
    this.$post('/api/vendor/file/createByKey', {
      filecode: d.code,
      caseid: this.props.caseDetail.id
    }).then(res => {
      hide()
      if (res.status === 1) {
        this.setState({
          visible: false
        })
        message.success('文书生成成功')
        this.getList()
      } else {
        message.warning(res.message)
      }
    }).catch(() => hide())
  }

  // 获取枚举的字典值
  getDictionary () {
    this.$get('/api/xapc/dictionary', {
      types: '文书类别'
    }).then(res => {
      if (res.status === 1) {
        // 设置枚举字典
        const dictionaries = this.formatDictionaries(res.data)
        const list = dictionaries['文书类别']
        this.setState({
          fileTypes: list.map(li => li.title)
        })
      } else {
        message.error(res.message)
      }
    })
  }

  // 格式化枚举字典
  formatDictionaries (dictionaries = []) {
    const result = {}
    dictionaries.forEach(d => {
      result[d.type] = d.list
    })
    return result
  }

  // 显示修改文书流水号
  showModifyNum (obj) {
    this.setState({
      modifyDoc: obj,
      numVisible: true
    })
  }

  // 修改文书流水号
  changeDocNum (d) {
    const hide = message.loading('提交中', 120)
    this.$put(`/api/vendor/document/updateSerialno/${this.state.modifyDoc.id}`, {
      serialno: d.serialno
    }).then(res => {
      hide()
      if (res.status !== 1) {
        return message.warning(res.message)
      }
      this.setState({
        numVisible: false,
        modifyDoc: null
      }, () => {
        this.getList()
      })
    }).catch(() => hide())
  }

  // 作废文书二次确认
  delConfirm (l) {
    confirm({
      icon: <ExclamationCircleOutlined />,
      content: `您确定要作废 ${l.title} 吗？`,
      onOk: () => {
        this.delRequest(l.id)
      }
    })
  }

  // 作废文书请求
  delRequest (id) {
    const hide = message.loading('作废中', 120)
    this.$put(`/api/vendor/document/cancelSerialno/${id}`)
      .then(res => {
        hide()
        if (res.status !== 1) {
          return message.warning(res.message)
        }
        this.getList()
      })
      .catch(() => hide())
  }

  changeName (name) {
    if (!name) {
      this.formRef.current.setFieldsValue({
        code: undefined
      })
    }
    const list = this.state.templateList
    for (let i = 0; i < list.length; i++) {
      const li = list[i]
      if (li.title === name) {
        this.formRef.current.setFieldsValue({
          code: li.code
        })
        break
      }
    }
  }

  componentDidUpdate (prev) {
    if (prev.caseDetail.id !== this.props.caseDetail.id) {
      this.getList()
    }
  }

  componentDidMount () {
    if (this.props.caseDetail.id) {
      this.getList()
    }
    this.getDictionary()
    this.getTemplateList()
  }

  renderModal () {
    return (
      <Modal
        title='新增文书'
        open={this.state.visible}
        maskClosable={false}
        onOk={() => this.formRef.current.submit()}
        onCancel={() => this.setState({ visible: false })}
        destroyOnClose
      >
        <Form name='add-doc-by-template' ref={this.formRef} onFinish={d => this.createDocumentByTemplate(d)}>
          <Item name='code' noStyle><span /></Item>
          <Item name='name' label='文书模板' rules={[{ required: true, message: '文书模板不能为空' }]}>
            <Select placeholder='请选择文书模板' showSearch onChange={e => this.changeName(e)} allowClear>
              {this.state.templateList.map(li => <Option key={li.id} value={li.title}>{li.title}</Option>)}
            </Select>
          </Item>
        </Form>
      </Modal>
    )
  }

  renderChangeNoModal () {
    return (
      <Modal
        title='修改流水号'
        open={this.state.numVisible}
        maskClosable={false}
        onOk={() => this.numFormRef.current.submit()}
        onCancel={() => this.setState({ numVisible: false })}
        destroyOnClose
      >
        <Form name='modify-doc-by-template' labelCol={{ flex: '100px' }} initialValues={this.state.modifyDoc} ref={this.numFormRef} onFinish={d => this.changeDocNum(d)}>
          <Item name='title' label='文书名称'>
            <Text />
          </Item>
          <Item name='serialno' label='文书流水号' rules={[{ required: true, message: '文书流水号不能为空' }]}>
            <InputNumber placeholder='请输入文书流水号' className={style.full} />
          </Item>
        </Form>
      </Modal>
    )
  }

  render () {
    const list = this.state.list.filter(li => (li.type || []).indexOf(this.state.type) !== -1)
    return (
      <div className={style.container}>
        {this.renderModal()}
        {this.renderChangeNoModal()}
        <div className={style.header}>
          <span className={style.title}>案件文书</span>
          <Space size='middle'>
            <Button type='primary' disabled={!this.props.editable} onClick={() => this.setState({ visible: true })}>新增文书</Button>
            <Radio.Group onChange={v => this.changeStatus(v)} value={this.state.type}>
              <Radio.Button value=''>全部</Radio.Button>
              {this.state.fileTypes.map(li => (
                <Radio.Button key={li} value={li}>{li}</Radio.Button>
              ))}
            </Radio.Group>
          </Space>
        </div>
        <Table loading={this.state.loading} rowKey={l => l.id} columns={columns.call(this)} dataSource={list} pagination={false} />
      </div>
    )
  }
}

CaseDocument.propTypes = {
  editable: PropTypes.bool
}
CaseDocument.defaultProps = {
  editable: false
}

const mapState = mapStateToProps(function (state) {
  return {
    userInfo: state.basic.userInfo
  }
})

const mapDispatch = mapDispatchToProps(function (dispatch) {
  return {

  }
})

export default connect(mapState, mapDispatch)(CaseDocument)
